Page({
  data: {
    userInfo: {
      avatar: '',
      name: '管理员',
      phone: '13800138000'
    },
    showModal: false,
    isPasswordModal: false,
    editField: '',
    editValue: '',
    passwordForm: {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    }
  },

  onLoad() {
    const app = getApp()
    const defaultAvatar = app.globalData.defaultAvatarUrl
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: {
          ...this.data.userInfo,
          ...app.globalData.userInfo,
          avatar: app.globalData.userInfo.avatarUrl || defaultAvatar
        }
      })
    } else {
      this.setData({
        'userInfo.avatar': defaultAvatar
      })
    }
  },

  showEditModal(e) {
    const field = e.currentTarget.dataset.field
    const value = this.data.userInfo[field]
    this.setData({
      showModal: true,
      isPasswordModal: false,
      editField: field,
      editValue: value
    })
  },

  showPasswordModal() {
    this.setData({
      showModal: true,
      isPasswordModal: true,
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
    })
  },

  hideModal() {
    this.setData({
      showModal: false,
      isPasswordModal: false,
      editField: '',
      editValue: '',
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
    })
  },

  onInputChange(e) {
    this.setData({
      editValue: e.detail.value
    })
  },

  onPasswordInput(e) {
    const field = e.currentTarget.dataset.field
    this.setData({
      [`passwordForm.${field}`]: e.detail.value
    })
  },

  submitEdit() {
    if (!this.data.editValue.trim()) {
      wx.showToast({
        title: '输入不能为空',
        icon: 'none'
      })
      return
    }

    // 更新用户信息
    this.setData({
      [`userInfo.${this.data.editField}`]: this.data.editValue
    })

    wx.showToast({
      title: '修改成功',
      icon: 'success'
    })

    this.hideModal()
  },

  submitPassword() {
    const { oldPassword, newPassword, confirmPassword } = this.data.passwordForm

    if (!oldPassword || !newPassword || !confirmPassword) {
      wx.showToast({
        title: '请填写完整密码信息',
        icon: 'none'
      })
      return
    }

    if (newPassword !== confirmPassword) {
      wx.showToast({
        title: '两次输入的密码不一致',
        icon: 'none'
      })
      return
    }

    // 这里应该调用修改密码的接口
    wx.showToast({
      title: '密码修改成功',
      icon: 'success'
    })

    this.hideModal()
  },

  changeAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0]
        this.setData({
          'userInfo.avatar': tempFilePath
        })
      }
    })
  }
}) 